//
//  CCYUserAccountVM.swift
//  03.微博
//
//  Created by 蔡承毅 on 16/9/23.
//  Copyright © 2016年 IOS. All rights reserved.
//

import UIKit

class CCYUserAccountVM: NSObject {
    
    static let shared: CCYUserAccountVM = CCYUserAccountVM()
    
    var userAccount: CCYUserAccount?
    
    let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last! + "/userAccount.plist"
    
//    var ueserAccount: CCYUserAccount?
    
    var isUserLogin:Bool {
        get{
            return userAccount != nil
        }
    }

    fileprivate override init() {
        super.init()
        
        userAccount = loadAccount()
    }
    
    
    func loadAccessToken(code: String, completion:@escaping (Error?) -> Void){
        let urlSting = "https://api.weibo.com/oauth2/access_token"
        let parameters = [
            "client_id": client_id,
            "client_secret": client_secret,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": redirect_uri
        ]
        
        
        CCYNetworkTool.shared.request(method: .POST, URLString: urlSting, parameters: parameters, progress: nil, success: { (_, responseObject) in
            print("获取到了accessToken\(responseObject)")
            let dict = responseObject as! [String: Any]
            ///字典转模型
            let userAccount = CCYUserAccount(dict: dict)
            print("userAccount = \(userAccount)")
            
            NSKeyedArchiver.archiveRootObject(userAccount, toFile: self.path)
            
            completion(nil)
        }) { (_, error) in
            print("获取accessToken错误 \(error)")
            completion(error)
        }
    }
    
    private func loadAccount() -> CCYUserAccount? {
        let account = NSKeyedUnarchiver.unarchiveObject(withFile: path) as? CCYUserAccount
        
        if let acc = account {
            let date = Date()
            if acc.expiresDate?.compare(date) == ComparisonResult.orderedDescending {
                return acc
            }
        }
        return nil
    }
    
    func loadUserInfo(completion:@escaping (Error?) -> Void) -> Void {
        let urlString = "users/show.json"
        
        guard let access_token = userAccount?.access_token,
            let uid = userAccount?.uid else{
                print("access_token没有值 或 uid没有值")
                return
        }
        
        let parameter = [
            "access_token": access_token,
            "uid": uid
        ]
        
        CCYNetworkTool.shared.request(method: .GET, URLString: urlString, parameters: parameter, progress: nil, success: { (_, responseObject) in
//            print("获取用户数据成功了\(responseObject)")
            let dict = responseObject as! [String: Any]
            self.userAccount?.screen_name = dict["screen_name"] as? String
            self.userAccount?.avatar_large = dict["avatar_large"] as? String
            
            NSKeyedArchiver.archiveRootObject(self.userAccount!, toFile: self.path)
            completion(nil)
            }) { (_, error) in
              completion(error)
        }
        
        
    }

}
